package com.contest.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.contest.dao.SessionInfoDao;
import com.contest.entity.BettingRecord;
import com.contest.entity.RoomInfo;
import com.contest.entity.SessionInfo;
import com.contest.service.BettingRecordService;
import com.contest.service.RoomInfoService;
import com.contest.service.SessionInfoService;
import com.contest.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * ${table.comment}  服务实现类
 * </p>
 *
 * @author yfl
 * @since ${date}
 */
@Service
public class SessionInfoServiceImpl extends  ServiceImpl<SessionInfoDao, SessionInfo> implements SessionInfoService {

    @Autowired
    BettingRecordService bettingRecordService;
    @Autowired
    RoomInfoService roomInfoService;
    @Autowired
    SettlementService settlementService;


    @Override
    public boolean updateResult(SessionInfo sessionInfo) {
        //单场胜负结果  -1:A胜  0:比赛中  1:B胜
        float singleSizeScale = sessionInfo.getFdSingleSizeScale().floatValue();
        float singleSpecialScale = sessionInfo.getFdSingleSpecialScale().floatValue();
        int result = sessionInfo.getFdSingleResult();
        int totalKill = 0;
        RoomInfo roomInfo = roomInfoService.selectById(sessionInfo.getFdRoomId());
        if(result != 0 && result != -2){
            if(result == -1){
                //A胜
                float singleScale = sessionInfo.getFdSingleAScale().floatValue();
                String clanAId = roomInfo.getFdClanAId();
                computeSingle(sessionInfo.getFdId(),clanAId,singleScale);
                sessionInfo.setFdSingleResult(-1);
                roomInfo.setFdClanAWinNum(BigDecimal.valueOf(roomInfo.getFdClanAWinNum().intValue()+1));
                sessionInfo.setFdSingleIsSettle(1);
            }else if(result == 1){
                //B胜
                float singleScale = sessionInfo.getFdSingleBScale().floatValue();
                String clanBId = roomInfo.getFdClanBId();
                computeSingle(sessionInfo.getFdId(),clanBId,singleScale);
                sessionInfo.setFdSingleResult(1);
                roomInfo.setFdClanBWinNum(BigDecimal.valueOf(roomInfo.getFdClanAWinNum().intValue()+1));
                sessionInfo.setFdSingleIsSettle(1);

            }
            int aKillNum = sessionInfo.getFdSingleClanAKillNum();
            int bKillNum = sessionInfo.getFdSingleClanBKillNum();
            totalKill = (aKillNum + bKillNum);
            settlementService.computeSize(totalKill+"",sessionInfo.getFdId(),singleSizeScale);
            settlementService.computeSpecial(totalKill+"",singleSpecialScale,sessionInfo.getFdId());

            Integer roomTotalKill =  roomInfo.getFdTotalKill();
            roomTotalKill = roomTotalKill != null ? roomTotalKill : 0;
            roomInfo.setFdTotalKill(roomTotalKill + totalKill);
            roomInfoService.updateById(roomInfo);
            this.updateById(sessionInfo);
        }else
        {
            this.updateById(sessionInfo);
        }


        return true;
    }

    @Override
    public void getSessionInfosByRoom(HttpServletRequest request, Map msg)  {

        String fdId = request.getParameter("fdId");
        BigInteger roomId = new BigInteger(fdId);
        RoomInfo roomInfo = roomInfoService.selectById(roomId);
        EntityWrapper<SessionInfo> ewSessionInfo = new EntityWrapper<SessionInfo>();
        ewSessionInfo.eq("fd_room_id" , roomId);
        ewSessionInfo.orderBy("fd_session_num" , true);
        List<SessionInfo> list = this.selectList(ewSessionInfo);

        List<Map> sessionsList = new ArrayList<>();
        //A、B的击杀数
        Integer totalAKillNumbers = 0;
        Integer totalBKillNumbers = 0;
        //A 、B的胜场数
        Integer winANumbers = 0;
        Integer winBNumbers = 0;

        for(SessionInfo s : list)
        {
            Map sessionMap = new HashMap();
            sessionMap.put("sessionInfo" , s);
            String startTime = s.getFdSingleStartTime();
            String endTime = s.getFdSingleEndTime();
            Date currentDate = new Date();
            Integer raceResult = s.getFdSingleResult();
//            //raceResult:-2未开始，-1A队胜,0比赛中,1B队胜
//            //fd_single_result:   -1A队胜,0比赛中,1B队胜
//            if( 0 == s.getFdSingleResult())
//            {
//                SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date startDate = null;
//                try {
//                    startDate = dfs.parse(startTime);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                    msg.put("result" , R.error(5000 , "time parse"));
//                    return;
//                }
//
//                if(currentDate.compareTo(startDate) < 0)
//                    raceResult = 2;
//                else
//                    raceResult = 0;
//            }


            if(-1 == raceResult)
                winANumbers++;
            if(1 == raceResult)
                winBNumbers++;


            if(-2 != raceResult)
            {
                totalAKillNumbers = totalAKillNumbers + s.getFdSingleClanAKillNum();
                totalBKillNumbers = totalBKillNumbers + s.getFdSingleClanBKillNum();
            }


//            sessionMap.put("raceResult" , raceResult);
            sessionsList.add(sessionMap);
        }

        //letClan：让场队 -1A队 ，0 没有，1B队
        //letNum:让场数
        Integer letClan = 0;
        String letClanId = roomInfo.getFdLetClanId();
        String clanAId = roomInfo.getFdClanAId();
        String clanBId = roomInfo.getFdClanBId();
        BigDecimal letNum = roomInfo.getFdLetNum();
        if(letClanId.equals(clanAId))
            letClan = -1;
        else if(letClanId.equals(clanBId))
            letClan = 1;


        msg.put("letClan" , letClan);
        msg.put("letNum" , letNum.intValue());
        msg.put("winANumbers" , winANumbers);
        msg.put("winBNumbers" , winBNumbers);
        msg.put("totalAKillNumbers" , totalAKillNumbers);
        msg.put("totalBKillNumbers" , totalBKillNumbers);
        msg.put("roomInfo" , roomInfo);
        msg.put("sessionInfos" , sessionsList);
        msg.put("result" , new R());
    }

    @Override
    public void getSessionInfosBySession(HttpServletRequest request , Map msg ) {
        String fdId = request.getParameter("id");
        BigInteger sessionId = new BigInteger(fdId);
        SessionInfo sessionInfo = this.selectById(sessionId);
        Integer raceResult = sessionInfo.getFdSingleResult();
        //fd_single_result:   -1A队胜,0比赛中,1B队胜
        if(raceResult != 0)
        {
            msg.put("result" , R.error("比赛结束!"));
            return;
        }
        RoomInfo roomInfo = roomInfoService.selectById(sessionInfo.getFdRoomId());

        msg.put("sessionInfo" , sessionInfo);
        msg.put("roomInfo" , roomInfo);
        msg.put("result" , new R());
    }


    /**
     * 计算单场胜负
     *
     * @param singleScale
     */
    private void computeSingle(String roomId, String winId, float singleScale) {
        EntityWrapper<BettingRecord> recordEntityWrapper = new EntityWrapper<BettingRecord>();
        recordEntityWrapper.addFilter("fd_type={0} and fd_room_id={1} and fd_is_settlement={2}", 0, roomId, 0);
        List<BettingRecord> recordList = bettingRecordService.selectList(recordEntityWrapper);
        settlementService.computeWin(recordList,singleScale,winId);
    }
}
